package com.cloudkinto.service.platform.sync;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.dao.PlatformOrderSyncRecordItemDao;
import com.cloudkinto.entity.PlatformOrderSyncRecordDo;
import com.cloudkinto.dao.PlatformOrderSyncRecordDao;
import com.cloudkinto.entity.PlatformOrderSyncRecordItemDo;
import com.cloudkinto.service.consumer.vo.orderSyncRecord.PlatformOrderSyncRecordReq;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.platform.PlatformStoreService;
import com.cloudkinto.service.platform.sync.vo.PlatformOrderSyncRecordRes;
import com.cloudkinto.service.platform.vo.store.PlatformStoreRes;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hua
 * @since 2025-06-17
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
@Slf4j
@RequiredArgsConstructor
public class PlatformOrderSyncRecordServiceImpl extends ServiceImpl<PlatformOrderSyncRecordDao, PlatformOrderSyncRecordDo> implements PlatformOrderSyncRecordService {
    private final PlatformStoreService platformStoreService;
    private final PlatformOrderSyncRecordItemDao platformOrderSyncRecordItemDao;


    @Override
    public int delete(Long id, Long userId) {
        PlatformOrderSyncRecordDo entityDo = baseMapper.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return baseMapper.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(PlatformOrderSyncRecordDo entityDo, Long userId) {

    }

    @Override
    public Object detail(Long id) {
        PlatformOrderSyncRecordDo entityDo =  baseMapper.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<PlatformOrderSyncRecordDo> wrapper = queryBuild(map);
        IPage<PlatformOrderSyncRecordDo> page = pageInit(map);
        page = this.page(page, wrapper);
        Long companyId = StringUtils.isNotBlank(map.get("companyId")) ? Long.parseLong(map.get("companyId")) : 0L;
        List<PlatformOrderSyncRecordRes> resList = handlerListAfter(page.getRecords(), companyId);
        PageResult result = new PageResult(resList, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }


    //查询分页列表之后对列表数据的处理
    private List<PlatformOrderSyncRecordRes> handlerListAfter(List<PlatformOrderSyncRecordDo> list, Long companyId){
        Map<Long, String> storeCodeMap = platformStoreService.getList(companyId).stream().collect(Collectors.toMap(PlatformStoreRes::getId, PlatformStoreRes::getStoreCode));
        List<PlatformOrderSyncRecordRes> result = new ArrayList<>();
        for (PlatformOrderSyncRecordDo entityDo : list) {
            PlatformOrderSyncRecordRes res = new PlatformOrderSyncRecordRes();
            BeanUtils.copyProperties(entityDo, res);
            res.setStoreCode(storeCodeMap.get(entityDo.getStoreId()));
            result.add(res);
        }
        return result;
    }

    private IPage<PlatformOrderSyncRecordDo> pageInit(Map<String, String> map) {
        IPage<PlatformOrderSyncRecordDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<PlatformOrderSyncRecordDo> queryBuild(Map<String, String> map) {
        QueryWrapper<PlatformOrderSyncRecordDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("storeId"))) {
            wrapper.eq("store_id", map.get("storeId"));
        }
        if (StringUtils.isNotBlank(map.get("platformCode"))) {
            wrapper.eq("platform_code", map.get("platformCode"));
        }
        if (StringUtils.isNotBlank(map.get("syncStatus"))) {
            wrapper.eq("sync_status", map.get("syncStatus"));
        }
        //时间条件
        if (StringUtils.isNotBlank(map.get("beginTime")) && StringUtils.isNotBlank(map.get("endTime"))) {
            wrapper.ge("create_time", map.get("beginTime"));
            wrapper.le("create_time", DateUtils.addOneDay(map.get("endTime"), 1));
        }
        else {
            wrapper.ge("create_time", DateUtils.addOneDay(DateUtils.dateFormatToString(new Date()), -30));
        }
        wrapper.eq("company_id", map.get("companyId"));
        wrapper.orderByDesc("id");
        return wrapper;
    }



    @Override
    public void updateRecord(Long id, Integer syncStatus, String failReason) {
        LambdaUpdateWrapper<PlatformOrderSyncRecordDo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PlatformOrderSyncRecordDo::getId, id);
        updateWrapper.set(PlatformOrderSyncRecordDo::getSyncStatus, syncStatus);
        updateWrapper.set(PlatformOrderSyncRecordDo::getFailReason, failReason);
        this.update();
    }


    @Override
    public void updateSyncRecord(PlatformOrderSyncRecordReq req) {
        if (req == null || req.getId() == null) {
            return;
        }
        LambdaUpdateWrapper<PlatformOrderSyncRecordDo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PlatformOrderSyncRecordDo::getId, req.getId());
//        updateWrapper.set(PlatformOrderSyncRecordDo::getFailReason, null);
        updateWrapper.set(PlatformOrderSyncRecordDo::getSyncStatus, req.getSyncStatus());
        updateWrapper.set(req.getFinishTime() != null, PlatformOrderSyncRecordDo::getFinishTime, req.getFinishTime());
        updateWrapper.set(req.getExecuteTime() != null, PlatformOrderSyncRecordDo::getExecuteTime, req.getExecuteTime());
        updateWrapper.set(req.getOrderCount() != null, PlatformOrderSyncRecordDo::getOrderCount, req.getOrderCount());
        updateWrapper.set(req.getBeginTime() != null, PlatformOrderSyncRecordDo::getBeginTime, req.getBeginTime());
        updateWrapper.set(req.getEndTime() != null, PlatformOrderSyncRecordDo::getEndTime, req.getEndTime());
        updateWrapper.set(req.getFailReason() != null, PlatformOrderSyncRecordDo::getFailReason, req.getFailReason());
        baseMapper.update(null, updateWrapper);

        if (!CollUtil.isEmpty(req.getSyncItems())) {
            //插入同步项
            List<PlatformOrderSyncRecordItemDo> syncItems = req.getSyncItems().stream().map(item -> new PlatformOrderSyncRecordItemDo(req.getId(), item.getPlatformOrderNo(), item.getPlatformOrderId(), item.getStoreId(), item.getCompanyId())).collect(Collectors.toList());
            platformOrderSyncRecordItemDao.batchInsert(syncItems);
        }
    }

}
